package com.duowan.realtime.server.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import com.duowan.datawarehouse.util.FileUtil;

public class ExpandFileUtils {

	/**
	 * file object
	 * @param file
	 * @param obj must implement Serializable interface
	 * @throws IOException 
	 */
	public static void writeObjectToFile(File file, Object obj) throws IOException{
		
		if (! file.getParentFile().exists()) {
			FileUtils.forceMkdir(file.getParentFile());
		}
		FileOutputStream fos = new FileOutputStream(file, false);
		writeObjectToFile(obj, fos);
	}
	
	private static void writeObjectToFile(Object obj, OutputStream os) throws IOException  {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(os);
			oos.writeObject(obj);
			oos.flush();
		} finally{
			IOUtils.closeQuietly(oos);
		}
		
	}
	
	public static Object readObjectFromFile(File file) throws IOException, ClassNotFoundException{
		Object obj = new Object();
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			obj = ois.readObject();
		} finally{
			IOUtils.closeQuietly(ois);
		}
		return obj;
	}
}
